package com.webchat.common.service;

import com.webchat.common.util.DateUtils;
import com.webchat.common.util.SnowflakeIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

import static com.webchat.common.util.DateUtils.YYYYMMDD;

@Component
public class SnowflakeIdGeneratorService {

    @Autowired
    private RedisService redisService;

    /**
     * 基于雪花算法分布下唯一id生成器
     *
     * @return
     */
    public String generateId() {
        SnowflakeIdGenerator snowflakeIdGenerator = new SnowflakeIdGenerator(incrementId());
        return snowflakeIdGenerator.nextId() + "";
    }


    /**
     * 生成带前缀的id
     *
     * @param prefix
     * @return
     */
    public String generateId(String prefix) {

        return prefix + "-" + this.generateId();
    }

    private Long incrementId() {
        return redisService.increx("SnowflakeId", 1L);
    }

    public static void main(String[] args) {
        SnowflakeIdGenerator snowflakeIdGenerator = new SnowflakeIdGenerator(1);
        String prefix = DateUtils.getDate2String(YYYYMMDD, new Date());
        System.out.println("orderId : " + prefix + snowflakeIdGenerator.nextId());
    }
}
